import { View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";

import ByRow from "@/components/ui/ByRow";
import ByTag from "@/components/ui/ByTag";
import Money from "@/components/app/Money";
import Card from "@/components/common/Card";
import Page from "@/components/common/Page";
import ByCell from "@/components/ui/ByCell";
import ByText from "@/components/ui/ByText";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import Uploader from "@/components/app/Uploader";
import ByStepsItem from "@/components/ui/ByStepsItem";
import FormInput from "@/components/common/FormInput";
import ByImageGroup from "@/components/ui/ByImageGroup";
import TagRadioGroup from "@/components/app/TagRadioGroup";
import FormInputNumber from "@/components/common/FormInputNumber";

import useWorkflowDefinition from "@/hooks/useWorkflowDefinition";
import useFetch from "@/hooks/useFetch";
import useForm from "@/hooks/useForm";
import ApiFinance from "@/api/finance";

type FormModel = {
  /**
   * 申请金额
   */
  applyAmount: number;
  /**
   * 0 表示工程付款, 1.供应商材料款, 3.工人工资 7.售后维修费
   */
  billType: number;
  /**
   * 费用类别， 从付款模版获取
   */
  feeCategory?: string;
  files?: string[];
  /**
   * 意向客户ID
   */
  intentCustomerId: number;
  /**
   * 付款阶段
   */
  paymentStage?: string;
  /**
   * 备注
   */
  remark?: string;
  /**
   * 摘要, 从付款模版获取
   */
  summary: string;
  /**
   * 付款对象ID
   */
  tagetUserId: number;
  /**
   * 付款对象名称
   */
  tagetUserName: string;
  /**
   * 付款对象类型 0:施工人员,1:供应商，2:工人
   */
  tagetUserType: number;
  /**
   * 模板明细ID
   */
  templateDetailId?: number;
};

const rules = {
  // tagetUserId: { required: true, message: "请选择付款对象" },
  applyAmount: { required: true, message: "请输入付款金额" },
};

function getRemainAmount(data?: any) {
  if (!data) return 0;
  return data.payableAmount - data.paidAmount - data.appliedAmount;
}

export default () => {
  const { params } = useRouter();

  // 指定收款模板（结算尾款）
  const specialCode = params.specialCode || "";
  const intentCustomerId = Number(params.intentCustomerId);

  // 获取审批流模板 & 绑定审批流
  const [workflowList, { loading: loadingWl, bind }] = useWorkflowDefinition(
    { typeCode: "FI_ApplyPaymentBill" },
    {
      onSuccess(res: any, params: any[]) {
        Taro.showToast({ title: "提交成功" });
        setTimeout(() => {
          Taro.redirectTo({
            url: `detail?paymentBillId=${params[0]["businessId"]}&wl_id=${res.workflowInstanceId}`,
          });
        }, 1500);
      },
    }
  );

  // 获取模板类型
  const { data: templateData } = useFetch<any[]>(
    ApiFinance.getPaymentTemplate,
    {
      defaultParams: [{ intentCustomerId }],
      onAfter: (res: any) =>
        specialCode
          ? res.details.filter((e) => e.specialCode == specialCode)
          : res.details,
      onSuccess(res) {
        const { templateDetailId, itemName } = res[0];
        setModel({ templateDetailId, summary: itemName });
      },
    }
  );

  // 提交表单
  const { loading, model, setModel, submit } = useForm<FormModel>(
    ApiFinance.savePaymentApply,
    {
      rules,
      defaultModel: {
        files: [],
        billType: 0,
        intentCustomerId,
      },
      onSuccess(res) {
        bind({
          intentCustomerId,
          businessId: res.paymentBillId + "",
        });
      },
    }
  );

  const templateDataItem = templateData?.find(
    (e) => e.templateDetailId === model.templateDetailId
  );

  const remainAmount = getRemainAmount(templateDataItem);

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByButton
            size="large"
            className="w-2/3"
            loading={loading || loadingWl}
            onClick={() => submit()}
          >
            提交申请
          </ByButton>
        }
      >
        <Card className="m-3">
          <ByCell label="费用类型" vertical requierd>
            {templateData && (
              <TagRadioGroup
                options={templateData}
                labelKey="itemName"
                valueKey="templateDetailId"
                value={[model.templateDetailId]}
                onChange={([e], item) =>
                  setModel({ templateDetailId: e, summary: item.itemName })
                }
              />
            )}
          </ByCell>

          <ByRow
            className="text-center bg-page rounded-md p-3"
            content="between"
          >
            <View>
              <Money value={templateDataItem?.payableAmount} />

              <ByText block size="sm" type="third">
                应付款
              </ByText>
            </View>

            <View>
              <Money value={templateDataItem?.paidAmount} />

              <ByText block size="sm" type="third">
                已付款
              </ByText>
            </View>

            <View>
              <Money value={templateDataItem?.appliedAmount} />
              <ByText block size="sm" type="third">
                已申请
              </ByText>
            </View>
          </ByRow>

          <ByCell label="剩余金额">
            <Money value={remainAmount} />
          </ByCell>

          <ByCell label="申请金额" vertical requierd>
            <FormInputNumber
              prefix="¥"
              placeholder="输入金额，不可>剩余金额"
              onChange={(e) => setModel({ applyAmount: e })}
            />
          </ByCell>

          <ByCell label="照片" vertical>
            <ByImageGroup
              showDelete
              urls={model.files}
              onChange={(e) => setModel({ files: e })}
              slotFooter={
                <Uploader
                  onSuccess={(e) => setModel({ files: model.files!.concat(e) })}
                />
              }
            />
          </ByCell>

          <ByCell label="备注" vertical>
            <FormInput
              type="textarea"
              placeholder="输入备注"
              value={model.remark}
              onChange={(e) => setModel({ remark: e })}
            />
          </ByCell>
        </Card>

        <Card className="m-3">
          <ByText size="sm" type="second" className="mb-3">
            审批流程
          </ByText>

          {workflowList[0]?.steps?.map((item) => (
            <ByStepsItem
              key={item.nodeId}
              title={item.nodeName}
              date={item.approvers.length > 0 ? "1人通过即可" : ""}
            >
              <BySpace gap={8}>
                {item.approvers?.map((approver) => (
                  <ByTag key={approver.actorId} variant="outline" size="small">
                    {approver.actorName}
                  </ByTag>
                ))}
              </BySpace>
            </ByStepsItem>
          ))}
        </Card>
      </Page>
    </>
  );
};
